package com.restfinder.user.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import com.restfinder.common.dao.StandardDAO;
import com.restfinder.user.model.Role;
import com.restfinder.user.model.User;

@Repository
@Slf4j
public class UserDAO extends StandardDAO<User> implements UserDetailsService {
	
	private static final long serialVersionUID = 1L;

	@Override
	public Class getEntityClass() {
		return User.class;
	}


	public boolean isUsernameUnique(String login){
   	 	
   	 	Session session = sessionFactory.getCurrentSession();
		SQLQuery query = session.createSQLQuery("SELECT id from users where username=:username");
		query.setString("username", login);
		Object result = query.uniqueResult();
		return result == null ? true : false;		
    }
	
	public User getUserByUsername(String username) {
   	 Query query = sessionFactory.getCurrentSession().createQuery("from User where username=:username").setString("username", username);
   	 User user = (User) query.uniqueResult();
	 return user;
   }


	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User domainUser = getUserByUsername(username);
		return new org.springframework.security.core.userdetails.User(domainUser.getUsername(), 
				domainUser.getPassword(), domainUser.isEnabled(), true, true, true, getAuthorities(domainUser.getRoles()));
	}
	
	private Collection<? extends GrantedAuthority> getAuthorities(
			List<Role> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for(Role role : roles){
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
		return authorities;
	}

}
